from kivy.app import App
from kivy.uix.dropdown import DropDown
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.button import Button
from matplotlib.pyplot import close
import serial
import serial.tools.list_ports


class HallDiv(BoxLayout):
    baud_value = 115200  # 实际波特率
    com_value = 0  # 实际串口号
    serial_switch_status = True  # 串口开关状态开关true/false

    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        global config_dict
        global ser
        self.ser_con = ser
        if config_dict["COM"] != '':
            self.ids.com_scroll.text = config_dict["COM"]
            self.ids.serial_switch.text = "open"
            self.ids.serial_switch.color = 0, 1, 0, 1
            self.ids.baud_scroll.text = config_dict["baud"]
            self.serial_switch_status = True
            self.baud_value = config_dict["baud"]
            self.com_value = config_dict["COM"]
        else:
            self.ids.com_scroll.text = "None"
            self.ids.serial_switch.text = "close"
            self.ids.serial_switch.color = 1, 0, 0, 1
            self.serial_switch_status = False

    # 串口开关
    def openSerialHandle(self, widget):
        if self.baud_value == 0 or self.com_value == 0:
            print("前选择好串口和波特率,缺一不可")
            return
        else:
            if self.serial_switch_status:
                self.ids.serial_switch.text = "close"
                self.ids.serial_switch.color = 1, 0, 0, 1
                self.serial_switch_status = False
                serialHandle(False)
            else:
                self.serial_switch_status = True
                str = '"COM":"{}","baud":"{}"'.format(
                    self.com_value, self.baud_value)
                str = '{'+str+'}'
                print('打开串口', str)
                file = open('./config.txt', 'w+')
                str = file.write(str)
                file.close()
                self.ids.serial_switch.text = "open"
                self.ids.serial_switch.color = 0, 1, 0, 1
                self.serial_switch_status = True
                serialHandle(True)
            # 串口item选择好处理

    def comItemSelect(self, ui, text):
        self.ids.com_scroll.text = text
        self.com_value = text
        config_dict["COM"] = text

    # 波特率item选择好处理

    def baudItemSelect(self, ui, text):
        print("baud_item_select", text)
        self.ids.baud_scroll.text = text
        self.baud_value = text
        config_dict["baud"] = text

    # 点击选择串口按钮处理
    def openComHandle(self, widget):
        # COM口列表
        list_disp = DropDown()
        global port_array
        for index in range(len(port_array)):
            item = Button(text=port_array[index],
                          size_hint_y=None, height=44)
            item.bind(on_release=lambda item: list_disp.select(item.text))
            list_disp.add_widget(item)
        list_disp.bind(on_select=self.comItemSelect)
        list_disp.open(widget)

    # 点击选择波特率按钮处理
    def openBaudHandle(self, widget):
        # baud波特率列表
        baud_list_disp = BaudListDiv()
        baud_list_disp.bind(on_select=self.baudItemSelect)
        baud_list_disp.open(widget)

    def ledButtonHandle(self, widget):
        print('ledButtonHandle', self.baud_value, self.com_value)


# 波特率容器
class BaudListDiv(DropDown):
    def __init__(self, **kwargs):
        super().__init__(**kwargs)


class SerialLedApp(App):
    def build(self):
        return HallDiv()


def serialHandle(status):
    global ser
    if status:
        if ser:
            ser.open()
        else:
            ser = serial.Serial(port=config_dict["COM"], baudrate=config_dict["baud"], parity=serial.PARITY_NONE,
                                stopbits=serial.STOPBITS_ONE, timeout=1, rtscts=False)

    else:
        ser.close()


if __name__ == '__main__':
    # 读取之前的串口配置，免得每次都要打开都要选串口和波特率.
    file = open('./config.txt', 'r')
    str = file.read()
    if str != '':
        config_dict = eval(str)
    file.close()

    # 列出所有当前的com口
    port_list = list(serial.tools.list_ports.comports())
    port_count = 0
    port_len = len(port_list)
    port_array = []
    while port_count < port_len:
        comAttr = list(port_list[port_count])
        port_array.append(comAttr[0])
        port_count = port_count + 1

    # 判断先前的串口是否现在还存在,不存在的话返回空给config_dict["COM"]
    port_count = 0
    while port_count < port_len:
        if config_dict["COM"] == port_array[port_count]:
            break
        else:
            if port_count == port_len - 1:
                config_dict["COM"] = ''
        port_count = port_count + 1

    print("串口情况:", config_dict["COM"])

    ser = False
    if config_dict["COM"] != '':
        serialHandle(True)

    SerialLedApp().run()
